
# coding: utf-8

# In[21]:


import QUANTAXIS as QA
import pandas as pd
import tushare as ts
import datetime as dt

hs300 = ts.get_hs300s()
sz500 = ts.get_zz500s()
# all = pd.concat([hs300, sz500])
codes = hs300['code'].to_list()
codes = codes[180:200]
# data = QA.QA_fetch_stock_min_adv(['600496', '300044', '601633'], '2019-07-01', '2020-03-03', '30min')
data = QA.QA_fetch_stock_day_adv(['600496', '300044', '601633', '002415', '000100', '300118', '000333'], '2019-03-01', '2020-03-17')
# data = QA.QA_fetch_stock_day_adv(codes, '2019-01-01', '2020-03-17')

ind = data.add_func(QA.QA_indicator_THS_JMDD)

# buy = QA.CROSS(ind.V3, ind.V4)
# # sell = QA.CROSS(ind.V4, ind.V3)

User = QA.QA_User(username='quantaxis', password='quantaxis')
Portfolio = User.new_portfolio('qatestportfolio')
Account = Portfolio.new_account(account_cookie='juemidingdi' ,init_cash=100000,
                        frequence=QA.FREQUENCE.THIRTY_MIN)
Broker = QA.QA_BacktestBroker()

QA.QA_SU_save_strategy(Account.account_cookie,
                       Account.portfolio_cookie, Account.account_cookie, if_save=True)

_date = None
# _date_today = dt.date(2020, 3, 12)
for items in data.panel_gen:
    if _date != items.date[0]:
        print('try to settle')
        _date = items.date[0]
        # tmp = dt.date.fromtimestamp(_date.timestamp())
        # if tmp < _date_today:
        #     continue
        Account.settle()
    # if _date == _date_today.
    for item in items.security_gen:
        if item.index.levels[0][0] not in ind.index.levels[0]:
            continue
        a = 1000
        close = item.CLOSE.iloc[0]
        if close > 100:
            a = 100
        elif item.CLOSE.iloc[0] > 20:
            a = 100
        elif item.CLOSE.iloc[0] > 10:
            a = 400
        if ind.loc[item.index].B.iloc[0] > 0:
            order = Account.send_order(
                code=item.code[0],
                time=item.datetime[0],
                amount=a,
                towards=QA.ORDER_DIRECTION.BUY,
                price=0,
                order_model=QA.ORDER_MODEL.CLOSE,
                amount_model=QA.AMOUNT_MODEL.BY_AMOUNT
            )
            if order:
                Broker.receive_order(QA.QA_Event(order=order, market_data=item))
                trade_mes = Broker.query_orders(Account.account_cookie, 'filled')
                res = trade_mes.loc[order.account_cookie, order.realorder_id]
                print('buy')
                order.trade(res.trade_id, res.trade_price,
                            res.trade_amount, res.trade_time)
        elif ind.loc[item.index].S.iloc[0] > 0:
            if Account.sell_available.get(item.code[0], 0) > 0:

                order1 = Account.send_order(
                    code=item.code[0],
                    time=item.datetime[0],
                    amount=a,
                    towards=QA.ORDER_DIRECTION.SELL,
                    price=0,
                    order_model=QA.ORDER_MODEL.CLOSE,
                    amount_model=QA.AMOUNT_MODEL.BY_AMOUNT
                )
                if order1:
                    Broker.receive_order(QA.QA_Event(
                        order=order1, market_data=item))
                    trade_mes = Broker.query_orders(
                        Account.account_cookie, 'filled')
                    res = trade_mes.loc[order1.account_cookie, order1.realorder_id]
                    print('sell')
                    order1.trade(res.trade_id, res.trade_price,
                                res.trade_amount, res.trade_time)


print(Account.history_table)
r = QA.QA_Risk(Account)
r.plot_assets_curve().show()
print(r.profit_construct)
Account.save()
r.save()
